#include "hex.h"
#include "../include/HashTable.h"

int HexEncode(const STD_BUFFER& bufIn, string& strOut, int iLow)
{
    return HexEncode(bufIn.data(), bufIn.size(), strOut, iLow);
}

int HexEncode(const BYTE* data, int iLen, string& strOut, int iLow)
{
    vector<char> objOut;

    objOut.resize(iLen * 2);
    int iResult = HexEncode(data, iLen, objOut.data(), iLow);
    if (iResult < 0) return iResult;

    strOut = string(objOut.data(), iResult);
    return strOut.length();
}

int HexEncode(const BYTE* data, int iLen, char* pcOut, int iLow)
{
    U8 u8Data;
    const char* pcHex = g_caUpHex;

    if (iLow) pcHex = g_caLowHex;
    for (int i = 0; i < iLen; i++)
    {
        u8Data = data[i];
        pcOut[i * 2] = pcHex[u8Data >> 4];
        pcOut[i * 2 + 1] = pcHex[u8Data & 0x0F];
    }
    return iLen * 2;
}

int HexDecode(const string& strIn, STD_BUFFER& bufOut)
{
    return HexDecode(strIn.c_str(), strIn.length(), bufOut);
}

int HexDecode(const char* pcIn, int iLen, STD_BUFFER& bufOut)
{
    if (iLen < 0) iLen = strlen(pcIn);

    bufOut.resize(iLen / 2);

    return HexDecode(pcIn, iLen, bufOut.data());
}

int HexDecode(const char* pcIn, int iLen, BYTE* pOut)
{
    if(iLen < 0) iLen = strlen(pcIn);

    int iLenOut = iLen / 2;

    for(int i = 0; i < iLenOut; i++)
    {
        pOut[i] = HexDecode1(pcIn + (i * 2));
    }
    return iLenOut;
}

U8 HexDecode1(const char* pcHex) { return (g_u8aAsciiVal[(U8)pcHex[0]] << 4) | (g_u8aAsciiVal[(U8)pcHex[1]]); }
